<script lang="ts" setup>
import {quality} from 'artplayer/types/quality'
import Option from 'artplayer/types/option'
import Artplayer from 'artplayer'
import Hls from 'hls.js'
import {nextTick, onMounted, ref} from 'vue'

defineOptions({
	name: 'BaseVideo'
})

type TVideo = {
	artId: string
	config: Option
	setting_width?: number
	auto_playback_max?: number
}

const props = withDefaults(defineProps<TVideo>(), {
	setting_width: 180,
	auto_playback_max: 10
})

const artPlayer = ref<Artplayer>()
const emit = defineEmits(['stateChange', 'readyChange'])
// 播放m3u8的处理方式
const playM3u8 = (video: any, url: string, art: any) => {
	if (Hls.isSupported()) {
		if (art.hls) art.hls.destroy()
		const hls = new Hls()
		hls.loadSource(url)
		hls.attachMedia(video)
		art.hls = hls
		art.on('destroy', () => hls.destroy())
	} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
		video.src = url
	} else {
		art.notice.show = 'Unsupported playback format: m3u8'
	}
}
const options: Option = {
	theme: '#23ade5',
	fullscreen: true,
	autoPlayback: false,
	mutex: true,
	customType: {
		m3u8: playM3u8
	},
	...props.config
}

onMounted(() => {
	Artplayer.SETTING_WIDTH = props.setting_width // 设置面板的宽度单位为像素
	Artplayer.AUTO_PLAYBACK_MAX = props.auto_playback_max // 自动回放功能的最大记录数，默认为 10
	nextTick(() => {
		init()
	})
})

const init = () => {
	artPlayer.value = new Artplayer(options)
	artPlayer.value.on('ready', () => {
		emit('readyChange')
	})
	artPlayer.value.on('video:play', (state) => {
		emit('stateChange', {type: 'play', state})
	})
	artPlayer.value.on('video:pause', (state) => {
		emit('stateChange', {type: 'pause', state})
	})
	artPlayer.value.on('video:ended', (state) => {
		emit('stateChange', {type: 'ended', state})
	})
}

// 播放
const play = () => {
	artPlayer.value?.play()
}
// 暂停
const pause = () => {
	artPlayer.value?.pause()
}
// 切换播放和暂停
const toggle = () => {
	artPlayer.value?.toggle()
}
// 销毁播放器并从html中移除 false的话不移除
const destroy = (flag = true) => {
	artPlayer.value?.destroy(flag)
}
// 视频时间跳转，单位秒
const seek = (time: number) => {
	artPlayer.value!.forward = time
}
// 设置切换视频地址
const switchUrl = (url: string) => {
	artPlayer.value!.url = url
	// artPlayer.switchUrl(url);
}
// 获取当前播放时间和总时间
const getCurrentTime = () => {
	return {
		currentTime: artPlayer.value?.currentTime,
		duration: artPlayer.value?.duration //有的视频是没有时长的，例如直播中的视频或者没被解码完成的视频，这个时候获取的时长会是 0
	}
}
// 设置视频海报，只有在视频播放前才能看到海报效果
const setPoster = (url: string) => {
	artPlayer.value!.poster = url
}
// 动态设置画质列表
const setQuality = (quality: quality[]) => {
	artPlayer.value!.quality = quality
}

defineExpose({
	init,
	play,
	pause,
	toggle,
	destroy,
	seek,
	switchUrl,
	getCurrentTime,
	setPoster,
	setQuality
})
</script>

<template>
	<div :id="artId" class="z-ArtPlay"/>
</template>

<style lang="scss" scoped>
.z-ArtPlay {
	width: 100%;
	height: 100%;
}
</style>
